package com.yuyou.activity.comm.service.service;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;


@Service
public class HttpClientService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public String client(String url, Map<String, String> params) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder().retryOnConnectionFailure(true).connectTimeout(60, TimeUnit.SECONDS ).readTimeout(10,TimeUnit.SECONDS).build();
        FormBody.Builder formBody = new FormBody.Builder();
        for(Map.Entry<String,String> entry : params.entrySet() ){
            formBody.add(entry.getKey(),entry.getValue());
        }
        Request request = new Request.Builder().url(url).post(formBody.build()).build() ;
        Response response = client.newCall(request).execute();
        String result;
        String responseJson = JSON.toJSONString(response);
        if(response.code() >= 200 || response.code() < 300){
            result=response.body().string();
        }else{
            logger.warn("短信发送失败，返回保文："+responseJson);
            return null;
        }
        logger.info("短信服务返回参数:"+result+",状态码："+response.code());
        return result;
    }
}
